const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const DatabaseService = require('./DatabaseService');

class AuthService {
  static async register(username, email, password) {
    try {
      // 检查用户是否已存在
      const existingUser = await DatabaseService.getUserByUsername(username);
      if (existingUser) {
        throw new Error('Username already exists');
      }

      const existingEmail = await DatabaseService.getUserByEmail(email);
      if (existingEmail) {
        throw new Error('Email already exists');
      }

      // 哈希密码
      const saltRounds = 10;
      const passwordHash = await bcrypt.hash(password, saltRounds);

      // 创建用户
      const user = await DatabaseService.createUser(username, email, passwordHash);
      
      // 生成JWT令牌
      const token = jwt.sign(
        { userId: user.id, username: user.username },
        process.env.JWT_SECRET || 'default_secret_key',
        { expiresIn: '24h' }
      );

      return {
        success: true,
        message: 'User registered successfully',
        user: {
          id: user.id,
          username: user.username,
          email: user.email
        },
        token
      };
    } catch (error) {
      throw new Error(`Registration failed: ${error.message}`);
    }
  }

  static async login(username, password) {
    try {
      // 查找用户
      const user = await DatabaseService.getUserByUsername(username);
      if (!user) {
        throw new Error('Invalid username or password');
      }

      // 验证密码
      const isPasswordValid = await bcrypt.compare(password, user.password_hash);
      if (!isPasswordValid) {
        throw new Error('Invalid username or password');
      }

      // 生成JWT令牌
      const token = jwt.sign(
        { userId: user.id, username: user.username },
        process.env.JWT_SECRET || 'default_secret_key',
        { expiresIn: '24h' }
      );

      return {
        success: true,
        message: 'Login successful',
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          balance: user.balance
        },
        token
      };
    } catch (error) {
      throw new Error(`Login failed: ${error.message}`);
    }
  }

  static verifyToken(token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET || 'default_secret_key');
      return {
        success: true,
        userId: decoded.userId,
        username: decoded.username
      };
    } catch (error) {
      return {
        success: false,
        message: 'Invalid token'
      };
    }
  }
}

module.exports = AuthService;